package main

import (
	"log"
	"os"
	"runtime"
	"tbq/mqreceiver/lib"
)

type MessageBody struct {
	MessageJSON  string `json:"messageJson"`
	AppKey       string `json:"appKey"`
	BusinessName string `json:"businessName"`
	SyncFlag     int    `json:"syncFlag"`
}

var db *lib.DB
var receiverName, mqServerName, mqCenterName, driverName, dataSourceName string
var cfg *lib.Cfg = new(lib.Cfg)
var queues []lib.Queue

func init() {
	num := len(os.Args)
	if num != 2 {
		log.Fatal("参数不正确，请输入配置文件路径")
	}

	configFile := os.Args[1]
	cfg.SetFile(configFile)
	receiverName = cfg.GetValue("mq", "receiverName")
	mqServerName = cfg.GetValue("mq", "mqServerName")
	mqCenterName = cfg.GetValue("mq", "mqCenterName")
	driverName = cfg.GetValue("db", "driverName")
	dataSourceName = cfg.GetValue("db", "dataSourceName")

	lib.InitMQ(cfg.GetValue("mq", "url"))
	lib.Dbconn = lib.GetDb(driverName, dataSourceName)
	queues = lib.FetchAllQueue()
}

func main() {
	// log.Print("mqCenterName:", mqCenterName, " mqServerName:", mqServerName, "receiver ["+receiverName+"] starting ...")
	runtime.GOMAXPROCS(2)

	forever := make(chan bool)
	for _, queue := range queues {
		go listenQueue(queue, mqCenterName, mqServerName, receiverName)
	}

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func listenQueue(queue lib.Queue, mqCenterName, mqServerName, receiverName string) {
	log.Print("listenQueue:", queue)
	exchangeName := mqCenterName + "." + mqServerName
	exchangeType := "direct"
	queueName := queue.Name.String
	routingKey := queue.Name.String
	if queue.QueueType == "topic" {
		exchangeName = exchangeName + ".topic." + queueName
		exchangeType = "fanout"
		queueName = queueName + "." + receiverName
		routingKey = ""
	}
	msgs := lib.CreateMqConsume(exchangeName, exchangeType, queueName, routingKey)

	go func() {
		for msg := range msgs {
			log.Printf("0. Received a message: %s", msg)

			processer := lib.FetchOneProcesser(queue.ID)
			mb := msg.MB
			go func() {
				log.Printf("调取接口url:%s;;当前queue:%s", processer.CallUrl, queue.Name.String)
				body := lib.CallProcessor(processer, mb.MessageJSON, queue)
				if mb.SyncFlag == 1 {
					go func() {
						lib.CallbackSync(msg.ReplyTo, msg.CorrelationId, body)
					}()
				}
			}()
		}
		log.Print("监听异常断开，重新监听队列：", queue)
		listenQueue(queue, mqCenterName, mqServerName, receiverName)
	}()
}

/*
return new Result("00100", "不支持该种请求方式", null).toJSON(); get/port
                return new Result("00501", "Get方式调用接口失败", null).toJSON();
            return new Result("00502", "Get方式调用接口出错", null).toJSON();
            return new Result("00503", "调用混合队列出错", null).toJSON();
            return new Result("00504", "调用B2C接口出错", null).toJSON();
                return new Result("00506", "调用跨中心路由器失败", null).toJSON();
            return new Result("00507", "调用跨中心路由器出错", null).toJSON();

   status = "0";
   message = "不存在该消息队列";
   if (((end - begin) / 1000) > 20) {
    logger.info("-------------------------[同步调用回执超时]--------------------");
    return new Result("00600", "同步调用出错", null).toJSON();

                return new Result("1", "异步调用成功", null).toJSON();
            return new Result("00300", "发送消息到MQ失败", null).toJSON();
                return new Result("00600", "同步调用出错", null).toJSON();
                    getRequest().setAttribute("responseObj", Service.getErrorJSONString("99", "服务器内部错误"));
            sysErrorMsg.put("code", "00004");
            sysErrorMsg.put("msg", "方法名格式不正确");
                md5ErrorMsg.put("code", "00700");
                md5ErrorMsg.put("msg", "数据验密不通过");
                getRequest().setAttribute("responseObj", Service.getErrorJSONString("98", "无调用权限"));
*/
